package hangler

import (
	"article-hub/cache"
	"article-hub/models"
	pkg2 "article-hub/pkg"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func User(c *gin.Context) {
	username := c.PostForm("user_name")
	password := c.PostForm("password")

	var user models.User
	err := models.DB.Where("user_name = ?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "未找到该用户",
		})
		return
	}
	if pkg2.Init(password) != user.Password {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "登陆成功",
		})
		return
	}

}

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	img := c.PostForm("img")
	if title == "" || content == "" || img == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}
	data := models.Posts{
		Title:   title,
		Content: content,
		Img:     img,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	redis_key := "add_" + strconv.Itoa(int(data.ID))
	var posts models.Posts
	models.DB.Where("id = ?", data.ID).First(&posts)
	jsonData, _ := json.Marshal(posts)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return

}

func Load(c *gin.Context) {
	id := c.Query("id")
	var posts models.Posts
	err := models.DB.Where("id = ?", id).First(&posts).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "进入详情失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"codee": 200,
			"msg":   "进入详情成功",
			"data":  posts,
		})
		return
	}

}

func Del(c *gin.Context) {
	id := c.Query("id")
	err := models.DB.Where("id = ?", id).Delete(&models.Posts{}).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	redis_key := "del_" + id
	cache.Rdb.Del(cache.Ctx, redis_key)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return

}

func List(c *gin.Context) {
	var posts []models.Posts
	redis_key := "list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()

	if cacheData == "" {
		models.DB.Find(&posts)
		jsonData, _ := json.Marshal(posts)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &posts)
	}
	models.DB.Find(&posts)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": posts,
	})
	return
}
